<template>
  <Modal v-model:visible="showUsers" title="用户列表" :width="800" centered @ok="onConfirm">
    <Card size="small" class="share-card">
      <Table
        bordered
        size="small"
        :rowKey="getRowKey"
        :columns="columns"
        :data-source="users"
        :scroll="{ x: 500, y: tableHeight }"
        :pagination="pagerOption"
        :row-selection="{ columnWidth: 20, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="onPaged"
        @resizeColumn="resizeColumn"
      ></Table>
    </Card>
  </Modal>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { ref, reactive, inject, computed } from 'vue';
  import { Modal, Card, Table } from 'ant-design-vue';

  const $store = useStore();
  const $http = inject('$http');

  const $emits = defineEmits(['confirm']);
  const props = defineProps({
    roleId: { type: Number }
  });

  const showUsers = ref(false);

  const users = ref([]);
  const selectedRowKeys = ref([]);

  const pagerOption = reactive({
    current: 1,
    pageSize: 20,
    defaultPageSize: 20,
    total: 0
  });
  const so = reactive({
    level: '',
    keywords: ''
  });

  const columns = reactive([
    {
      title: '序号',
      width: 30,
      resizable: false,
      align: 'center',
      customRender: ({ index }) => (pagerOption.current - 1) * pagerOption.pageSize + index + 1
    },
    { title: '账号', width: 80, resizable: true, dataIndex: 'Account' },
    { title: '用户名', width: 50, resizable: true, dataIndex: 'UserName' },
    { title: '邮箱', width: 150, resizable: true, dataIndex: 'EMail' }
  ]);

  const tableHeight = computed(() => {
    return $store.state.area.content.height - 180;
  });

  function getRowKey(record) {
    return record.Id;
  }

  function resizeColumn(w, col) {
    col.width = w;
  }

  function onPaged(pg) {
    let index = 1;

    if (pg && pg.current) {
      index = pg.current;
      pagerOption.pageSize = pg.pageSize;
    }

    let searchObject = {
      pageIndex: index,
      pageSize: pagerOption.pageSize,
      account: so.account,
      userName: so.userName,
      roleId: props.roleId || null
    };

    $http.post('/api/rbac/users/search', searchObject).then(res => {
      users.value = res.datas;

      pagerOption.current = index || 1;
      pagerOption.total = res.total;
    });
  }

  function onSelectChange(keys) {
    selectedRowKeys.value = keys;
  }

  function show() {
    onPaged();

    showUsers.value = true;
  }

  function onConfirm() {
    $emits('confirm', selectedRowKeys.value);

    showUsers.value = false;
    selectedRowKeys.value.length = 0;
  }

  defineExpose({
    show
  });
</script>
